﻿using System;
using System.IO;
using Microsoft.Office.Interop.Excel;
using Application = Microsoft.Office.Interop.Excel.Application;
using _Application = Microsoft.Office.Interop.Excel._Application;

namespace MultiThumbnail.Converters
{
	/// <summary>
	/// To allow work it from service or IIS you need:
	/// 1. Run command dcomcnfg
	/// 2. Expand the Component Services->Computers->My Computer->DCOM Config (Службы компонентов->Компьютеры->Мой компьютер->Настройка DCOM
	/// 3. Find Microsoft Excel Application
	/// 4. Right mouse click->Properties. click the Identity tab. Check the "This user" checkbox.
	/// </summary>
    [Extension("XLSX;XLS;CSV")]
    class XlsThumbConverter:ThumbConverter
    {
        public override bool CreateMiniature(Stream fileStream, string resultPath)
        {
            return true;
        }

		protected override bool CreateMiniatureForFile(string path, string resultPath)
		{
		    string filePathToRemove = null;
		    try
		    {
                //if (ext == null || ext.TrimStart('.').ToUpperInvariant() != ConverterSettings.CurrentExtension)
                //{
		            filePathToRemove = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(path) + '.' + ConverterSettings.CurrentExtension);
		            File.Copy(path, filePathToRemove, true);
		            path = filePathToRemove;
		        //}
		        Convert(path, resultPath + ".pdf");
		        try
		        {
		            new PdfThumbConverter {ConverterSettings = ConverterSettings}.CreateMiniature(resultPath + ".pdf", resultPath);
		            return true;
		        }
		        finally
		        {
		            File.Delete(resultPath + ".pdf");
		        }
		    }
		    finally
		    {
                if (filePathToRemove != null)
		            File.Delete(filePathToRemove);
		    }
		}

		private static void Convert(string inputPath, string outputPath)
		{
           // Create an instance of Word.exe
            _Application excel = new Application();

		    // Make this instance of word invisible (Can still see it in the taskmgr).
		    excel.Visible = false;

		    var tMiss = Type.Missing;

		    //If you have an error do:
		    //
		    //    Start -> dcomcnfg.exe
		    //    Computer
		    //    Local Computer
		    //    Config DCOM
		    //    Search for Microsoft Excel Application -> Properties
		    //Tab Identity, change from Launching User to Interactive User 
		    var workBook = excel.Workbooks.Open(inputPath, 0, false, tMiss, tMiss,
		        tMiss, true, tMiss, tMiss, tMiss,
		        tMiss, tMiss, false, false);

		    workBook.Activate();
		    workBook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, outputPath);
		    excel.Quit();
		}
    }
}
